import os
import time
from decimal import Decimal

# Create your views here.
from django.db.models import Q, Case, When, IntegerField
from django.http import JsonResponse

#django模型
from bid.generate.models import ExProject, ExBidTeam, ExTeamQualification, ExTeamSocialInsurance

from zentao.settings import BIG_SAVE_FOLDER, ROOT_FOLDER

#对话生成
from bid.generate.tools.generate_project import generate_project
from bid.generate.tools.generate_pmProject import generate_pmProject

#业绩信息获取
def get_project(_type, ids, bid_id):
    # 格式化
    project_data = {}

    # 额外信息
    extra_data = {}

    if _type == 'pmProject':
        bid_team = ExBidTeam.objects.filter(bid=bid_id, position='项目负责人').select_related('account', 'account__IDCardFront',
                                                                                      'account__IDCardBack',
                                                                                      'account__degreeFile').first()
        # if not bid_team:
        #     return JsonResponse({'code': 0, 'msg': '不存在该id'})
        pm_name = ''
        professional = ''
        sex = ''
        degree = ''
        position = ''
        if bid_team:
            # 获取项目负责人信息
            pm = bid_team.account
            if pm:
                pm_name = pm.name
                professional = pm.professional
                sex = pm.sex
                degree = pm.degree
                position = bid_team.position

        # 获取项目负责人信息
        extra_data['pm'] = pm_name
        extra_data['professional'] = professional
        extra_data['sex'] = sex
        extra_data['degree'] = degree
        extra_data['position'] = position

        # 项目负责人其他信息
        extra_data['pm_info'] = {}

        # 身份证
        extra_data['pm_info']['身份证'] = []
        if bid_team.account.IDCardBack:
            extra_data['pm_info']['身份证'].append(os.path.join(ROOT_FOLDER, bid_team.account.IDCardBack.path))
        if bid_team.account.IDCardFront:
            extra_data['pm_info']['身份证'].append(os.path.join(ROOT_FOLDER, bid_team.account.IDCardFront.path))

        # 学历证书
        extra_data['pm_info']['学历证书'] = []
        if bid_team.account.degreeFile:
            extra_data['pm_info']['学历证书'].append(os.path.join(ROOT_FOLDER, bid_team.account.degreeFile.path))

        # 资格证书
        extra_data['pm_info']['资格证书'] = {}
        quas = ExTeamQualification.objects.filter(account=bid_team.account.account).select_related("file").distinct()
        for qua in quas:
            number = f"：{qua.number}" if qua.number else ""
            title = f"{qua.name}{number}"
            if qua.file.path:
                extra_data['pm_info']['资格证书'][title] = [os.path.join(ROOT_FOLDER, qua.file.path)]

        # 社保证明
        extra_data['pm_info']['社保证明'] = []
        insurances = ExTeamSocialInsurance.objects.filter(account=bid_team.account.account).select_related(
            "file").distinct() \
            .order_by('-year', '-month')
        for insurance in insurances[:3]:
            if insurance.file.path:
                extra_data['pm_info']['社保证明'].append(os.path.join(ROOT_FOLDER, insurance.file.path))

    # 查询公司业绩
    query = Q(id__in = ids)

    # 创建一个Case表达式用于排序
    preserved_order = Case(
        *[When(id=id, then=pos) for pos, id in enumerate(ids)],
        output_field=IntegerField()
    )

    if _type == 'project':
        projects = ExProject.objects.filter(query).select_related('companyChange','winBid', 'contractScan',
                                                'contractTransfer','acceptanceCert').all().distinct().order_by(preserved_order)
    else:
        projects = ExProject.objects.filter(query).select_related('contractScan','acceptanceCert').all().distinct().order_by(preserved_order)

    # 总金额
    total_amount = Decimal('0.0')

    # 获取所有项目的id
    project_ids = set()
    for i, project in enumerate(projects, start=1):

        # 如果关联项目不存在，则跳过
        if not project:
            continue

        project_ids.add(project.id)

        # 项目金额
        contractAmount = project.contractAmount if project.contractAmount else 0

        # 对方联系人
        counterpartContact = project.counterpartContact if project.counterpartContact else ''

        # 对方电话
        counterpartPhone = project.counterpartPhone if project.counterpartPhone else ''

        # 总金额
        total_amount += Decimal(str(contractAmount))

        if _type == 'project':
            info = {
                '序号': i,
                '项目名称': project.name if project.name else '',
                '项目地点': project.address if project.address else '',
                '合同(服务)对方名称': project.counterpartName if project.counterpartName else '',
                '对方联系人及电话': f'{counterpartContact}\n{counterpartPhone}',
                '合同金额(万元)': contractAmount,
                '项目描述': project.desc if project.desc else '',
                '备注': project.comment if project.comment else '',
            }

            # 附件信息
            en2zh = {
                "companyChange": "企业名称变更备案",
                "winBid": "中标通知书",
                "contractScan": "合同扫描件",
                "contractTransfer": "合同转签协议",
                "acceptanceCert": "验收证书",
                "invoice": "发票"
            }
            for key in ['companyChange', 'winBid', 'contractScan', 'contractTransfer', 'acceptanceCert','invoice']:
                file = eval(f'project.{key}')
                if file:
                    info[en2zh[key]] = os.path.join(ROOT_FOLDER, file.path)

        else:
            # 验收日期
            acceptanceDate = project.acceptanceDate
            if acceptanceDate:
                year = f'{acceptanceDate.year}年'
            else:
                year = ''

            info = {
                '序号': i,
                '项目名称': project.name if project.name else '',
                '合同名称': project.contractName if project.contractName else '',
                '甲方单位': project.counterpartName if project.counterpartName else '',
                '乙方项目负责人': extra_data['pm'],
                '项目验收年份': year,
                '项目金额（万元）': contractAmount
            }

            # 附件信息
            en2zh = {
                "contractScan": "合同关键页",
                "acceptanceCert": "验收证书"
            }
            for key in ['contractScan', 'acceptanceCert']:
                file = eval(f'project.{key}')
                if file:
                    info[en2zh[key]] = os.path.join(ROOT_FOLDER, file.path)

        project_data[project.id] = info

    # 总金额
    extra_data['total_amount'] = str(total_amount)

    # 获取项目的附件
    # query = Q(objectId__in=project_ids)
    # query &= Q(objectType='project')
    #
    # files = ExFile.objects.filter(query).all().distinct()
    #
    # for file in files:
    #     project_data[file.objectId][file.comment] = file.path

    # 转为列表
    project_data = list(project_data.values())

    # print(project_data)

    # # 文件存储位置
    save_folder = os.path.join(BIG_SAVE_FOLDER, _type)
    # 映射
    en2zh = {
        'project': '业绩',
        "pmProject": '负责人业绩'
    }
    now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    filename = f"{en2zh[_type]}生成_{now}.docx"
    save_path = os.path.join(save_folder, filename)
    if not os.path.isdir(save_folder):
        os.makedirs(save_folder)

    if _type == 'project':
        # generate_project(project_data[:2], extra_data, save_path)
        generate_project(project_data, extra_data, save_path, bid_id)
    else:
        # generate_pmProject(project_data[:2], extra_data, save_path)
        generate_pmProject(project_data, extra_data, save_path, bid_id)

    return filename, save_path